package com.briup.run.web.filter;

import com.briup.run.bean.Memberinfo;
import com.briup.run.constant.AutoLoginConstant;
import com.briup.run.service.MemberInfoService;
import com.briup.run.service.impl.MemberInfoServiceImpl;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @Auther: vanse(lc))
 * @Date: 2022/10/10-10-10-16:58
 * @Description：memer/*
 */
@WebFilter(value = "/member/*")
public class AutoLoginFilter implements Filter {
    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
        HttpSession session = request.getSession();
        Object memberinfoFromSession = session.getAttribute("memberinfo");
        if(memberinfoFromSession == null){
            // 获取cookie
            Cookie[] cookies = request.getCookies();
            String nameValue = ""; // nameCookie的值
            String passValue = ""; // nameCookie的值
            if(cookies != null && cookies.length > 0){
                for (Cookie cookie : cookies) {
                    // nameCookie
                    if(AutoLoginConstant.AUTO_NAME.equals(cookie.getName())){
                        nameValue = cookie.getValue();
                    }
                    if(AutoLoginConstant.AUTO_PASS.equals(cookie.getName())){
                        passValue = cookie.getValue();
                    }
                }
                // name和vlaue
                MemberInfoService service = new MemberInfoServiceImpl();
                // 自动登录的对象存到session
                Memberinfo memberinfo = service.login(nameValue, passValue);
                session.setAttribute("memberinfo",memberinfo);
            }

        }

        chain.doFilter(req, resp);
    }

    public void init(FilterConfig config) throws ServletException {

    }

}
